import os
import uuid
from flask import Blueprint, request, jsonify, send_from_directory
import subprocess
from app.database import get_db_connection

video_bp = Blueprint('video', __name__)

UPLOAD_FOLDER = '/home/user3/mmaction2_YF_2'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@video_bp.route('/upload-video', methods=['POST'])
def upload_video():
    try:
        if 'file' not in request.files:
            return jsonify({'success': False, 'message': '未选择文件'}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({'success': False, 'message': '未选择文件'}), 400

        ext = file.filename.rsplit('.', 1)[-1].lower()
        filename = f"{uuid.uuid4()}.{ext}"
        video_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(video_path)

        return jsonify({
            'success': True,
            'message': '上传成功',
            'video_name': filename,
            'videoUrl': f'/api/videos/{filename}'
        })
    except Exception as e:
        import traceback
        print("====上传异常====")
        print(e)
        traceback.print_exc()
        return jsonify({'success': False, 'message': '上传失败', 'error': str(e)}), 500

@video_bp.route('/videos/<path:filename>')
def serve_video(filename):
    # filename 可能是 xxx.mp4 或 xxx_output/xxx_combined1.mp4
    return send_from_directory(UPLOAD_FOLDER, filename)

@video_bp.route('/analyze-video', methods=['POST'])
def analyze_video():
    data = request.get_json()
    account = data.get('account')

    filename = data.get('filename')
    if not filename:
        return jsonify({'success': False, 'message': '缺少文件名'}), 400

    video_path = os.path.join(UPLOAD_FOLDER, filename)
    print("分析用视频路径：", video_path)
    print("文件是否存在：", os.path.exists(video_path))
    output_dir = os.path.join(UPLOAD_FOLDER, f"{filename}_output")
    os.makedirs(output_dir, exist_ok=True)

    script_path = '/home/user3/mmaction2_YF_2/express/run.sh'
    try:
        result = subprocess.run(
            ['bash', script_path, video_path, output_dir],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=600,
            encoding='utf-8',
            cwd='/home/user3/mmaction2_YF_2'
        )
        if result.returncode != 0:
            print("算法脚本stderr:", result.stderr)
            return jsonify({'success': False, 'message': '算法分析失败', 'error': result.stderr}), 500

        result_files = []
        # 先初始化变量为 None
        csv_path = None
        bar_img_path = None
        pie_img_path = None
        visualize_img_path = None
        analyzed_video_path = None

        for fname in os.listdir(output_dir):
            fpath = os.path.join(output_dir, fname)
            if os.path.isfile(fpath):
                url = f'/api/videos/{filename}_output/{fname}'
                if fname.lower().endswith('.csv'):
                    csv_path = url
                elif fname.lower().endswith('饼状图.png'):
                    bar_img_path = url
                elif fname.lower().endswith('雷达图.png'):
                    pie_img_path = url
                elif fname.lower().endswith('可视化.png'):
                    visualize_img_path = url
                elif fname.lower().endswith('.mp4'):
                    analyzed_video_path = url

        # 获取数据库连接和游标
        conn = get_db_connection()
        cursor = conn.cursor()

        # 输出当前要存入数据库的账号
        print(f"【分析入库】即将存入数据库的account：{account}")

        # 只插入一条记录
        cursor.execute(
            "INSERT INTO analysis_results9 (video_name, file_path, account, csv_path, bar_img_path, pie_img_path, visualize_img_path, analyzed_video_path) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
            (filename, analyzed_video_path, account, csv_path, bar_img_path, pie_img_path, visualize_img_path, analyzed_video_path)
        )

        conn.commit()
        cursor.close()
        conn.close()

        # 在分析成功后，查询所有分析结果并返回
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute(
                    "SELECT * FROM analysis_results9 WHERE video_name=%s AND account=%s", (filename, account)
                )
                results = cursor.fetchall()

        return jsonify({
            'success': True,
            'message': '分析成功',
            'results': results
        })
    except Exception as e:
        import traceback
        print("====分析异常====")
        print(e)
        traceback.print_exc()
        return jsonify({'success': False, 'message': '分析失败', 'error': str(e)}), 500

@video_bp.route('/get-history/<account>', methods=['GET'])
def get_history(account):
    print(f"【历史记录接口】收到的account参数：{account}")  # 新增输出
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "SELECT * FROM analysis_results9 WHERE account=%s ORDER BY id DESC", (account,)
    )
    results = cursor.fetchall()
    cursor.close()
    conn.close()
    return jsonify({'success': True, 'history': results})

@video_bp.route('/get-results/<account>', methods=['GET'])
def get_results(account):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "SELECT * FROM analysis_results9 WHERE account=%s ORDER BY id DESC", (account,)
        )
        results = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'results': results})
    except Exception as e:
        import traceback
        print("====get-results异常====")
        print(e)
        traceback.print_exc()
        return jsonify({'success': False, 'message': '查询失败', 'error': str(e)}), 500